
//@ts-check

const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"
export default class MyPromise {
    //Promise 状态
    status = PENDING;
    //成功之后的值
    value = undefined
    //失败的原因
    reason = undefined
    //成功回调
    successCallback = []
    //失败回调
    failCallback = []
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }

    }

    resolve = (value) => {
        if (this.status !== PENDING) return
        this.status = FULFILLED
        this.value = value
        // this.successCallback  && this.successCallback(this.value)
        while (this.successCallback.length) this.successCallback.shift()(this.value)
    }

    reject = (reason) => {
        if (this.status != PENDING) return
        this.status = REJECTED
        //保存失败的原因
        this.reason = reason
        // this.failCallback && this.failCallback(this.reason)
        while (this.failCallback.length) this.failCallback.shift()(this.reason)
    }

    then = (successCallback, failCallback) => {
        successCallback =successCallback ?successCallback: value => value
        failCallback = failCallback ? failCallback : reason => {throw reason}
        //判断状态
        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status == FULFILLED) {
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value)
                        resolvePromise(x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                })

            } else if (this.status == REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason)
                        resolvePromise(x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                })
            } else {
                //等待状态 存储状态
                //在Promise类中加入异步
                // this.successCallback = successCallback
                // this.failCallback = failCallback
                //  实现then方法多次调用添加多个处理函数
                //实现then方法的链式调用，then返回promise对象
                
                this.successCallback.push(()=>{
                    successCallback
                })
                this.failCallback.push((() => {
                    failCallback
                }))
            }
        })
        return promise2
    }


}

function resolvePromise(x, resolve, reject) {
    if (x instanceof MyPromise) {
        x.then(resolve, reject)
    } else {
        resolve(x)
    }
}
